<template>
	<div class="state-chart-box">
		<div id="stateChart"></div>
	</div>
</template>
<script setup>
import { ref, reactive } from "vue";
import echarts from "@/common/utils/echarts.js";

let dataArr = ref([]);
// let colorArr = ["#05CFF7", "#1978E5", "#EAB966", "#60B45E"];
let colorArr = [
	"#05cff7",
	"#1978e5",
	"#eab966",
	"#60b45e",
	"#becdd0",
	"#ea6666",
	"#ff3bba",
	"#b166ea",
];
let richColor = {};
colorArr.forEach((item, idx) => {
	richColor[`color${idx}`] = {
		color: item,
	};
});
let legendArr = ref([]);
let sum = 0;

let options = reactive({
	color: colorArr,
	legend: {
		top: "middle",
		left: "55%",
		data: legendArr.value,
		icon: "rect",
		itemWidth: 10, //正方形
		itemHeight: 10,
		itemGap: 20, //间距
		width: "20%", //组件宽度
		formatter: (name) => {
			let id = 0;
			let rate = "";
			dataArr.value.some((item, index) => {
				if (item.name === name) {
					id = index;
					rate = ((item.value / sum) * 100).toFixed(2) + "%";
					return true;
				}
			});
			return `${name}  {color${id}|${rate}}`;
		},
		textStyle: {
			color: "#D3E3FF",
			backgroundColor: "transparent",
			rich: {
				...richColor,
			},
		},
	},
	graphic: {
		elements: [
			{
				type: "circle",
				shape: {
					r: 60, //半径大小
				},
				style: {
					fill: {
						x: 1,
						y: 1,
						r: 1,
						colorStops: [
							{
								offset: 1,
								color: "rgba(50,171,241, .2)",
							},
							{
								offset: 0.5,
								color: "rgba(50,171,241, 0)",
							},
							{
								offset: 0,
								color: "rgba(50,171,241, .2)",
							},
						],
					}, // 填充颜色
				},
				left: "18.7%",
				top: "31.5%",
			},
		],
	},
	series: [
		{
			type: "pie",
			data: dataArr.value,
			// left: "10%",
			top: "25%",
			center: ["30%", "40%"], // 圆心
			radius: ["80%", "95%"], // 半径
			label: {
				show: false,
				position: "center",
			},
			labelLine: {
				show: false,
			},
			emphasis: {
				scaleSize: 8,
				label: {
					show: true,
					formatter: (param) => {
						return `{color${param.dataIndex}|${param.name}\n\n${param.value}人}`;
					},
					rich: richColor,
				},
			},
		},
	],
});

let stateChartRef = null;
let initStateChartData = (v = []) => {
	dataArr.value.splice(0);
	dataArr.value.push(
		...v.map(({ childcare_name, child_num }) => ({
			name: childcare_name,
			value: child_num,
		}))
	);
	legendArr.value = dataArr.value.map((item, i) => {
		sum += item.value;
		return {
			name: item.name,
		};
	});
	options.legend.data = legendArr.value;
	stateChartRef.setOption(options);
};
const initStateChart = (v) => {
	stateChartRef = echarts.init(document.getElementById("stateChart"));
	initStateChartData(v);
};
defineExpose({
	initStateChart,
});
</script>
<style lang="scss" scoped>
.state-chart-box {
	width: 100%;
	height: 100%;
	#stateChart {
		width: 100%;
		height: 100%;
	}
}
</style>
